package com.feihong.yw189.bluetooth.startreadcard;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

import com.feihong.yw189.bluetooth.bleutils.BleGlobUtils;
import com.feihong.yw189.bluetooth.bleutils.BleHttpUtils;
import com.feihong.yw189.bluetooth.listener.UpLoadListener;
import com.kaer.sdk.IDCardItem;
import com.kaer.sdk.bt.BtReadClient;
import com.kaer.sdk.utils.CardCode;
import com.kaeridcard.client.BtReaderClient;


/**
 * KT8003读卡
 * 2017/8/24
 * 张鹏
 */
public class Kt8003ConnectUtils {

    private BluetoothDevice remoteDevice;
    private String bleAddress;
    private BluetoothAdapter ba;
    private Context context;
    private Activity mActivity;

    private String name, sex, nation, id_num, address, sign_office, to, from, born;
    private String birth_year, birth_month, birth_day, sign_data, photoHeard;
    private Bitmap photo;
    private String bluetoothName = "";
    private BleHttpUtils bleHttpUtils;
    private Boolean mFlag = false;
    private Boolean flags;
    // 注册成功失败监听
    private UpLoadListener mOnUpLoadListener;
    private BtReadClient mBtReadClient;
    private String password;
    private ReadAsync async;
    private Handler kAmHandler;
    private String bleName;
    public Kt8003ConnectUtils(final Context context, BtReadClient mBtReadClient,
                              BluetoothAdapter ba, BluetoothDevice remoteDevice,
                              String bleName, String bleAddress,  final String bluetoothName,
                              Boolean flag, final UpLoadListener mOnUpLoadListener) {
        this.context = context;
        this.mActivity = (Activity) context;
        this.mBtReadClient = mBtReadClient;
        this.ba = ba;
        this.remoteDevice = remoteDevice;
        this.bleName = bleName;
        this.bleAddress = bleAddress;
        this.mFlag = flag;
        this.bluetoothName = bluetoothName;
        this.mOnUpLoadListener = mOnUpLoadListener;
    }

    public void connect(BtReaderClient mClient) {
        this.mClient = mClient;
        bleHttpUtils = new BleHttpUtils(context, bluetoothName, mFlag, new UpLoadListener() {
            @Override
            public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
                                    String nation, String sign_office, String name, String sign_data,
                                    String birth_year, String birth_month, String birth_day,
                                    Bitmap photo, String filePhoto, String idPath, String to,
                                    String from, String born, String photoHeard) {
                mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                        sign_office, name, sign_data, birth_year, birth_month, birth_day,
                        photo, filePhoto, idPath, to,
                        from, born, photoHeard);
                // 读卡成功需要断开连接
                stopConnect();
            }

            @Override
            public void onErrUpLoad(String err) {
                mOnUpLoadListener.onErrUpLoad(err);
                // 读卡失败需要断开连接
                stopConnect();
            }
        });
        flags = false;
        if (mBtReadClient.getBtState() == 0) {
            if (remoteDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
                // 已绑定的进入连接
                boolean b = mBtReadClient.connectBt(remoteDevice);
                if (b) {
                    // 子线程同步调用
                    async = new ReadAsync();
                    async.execute();
                } else {
                    mOnUpLoadListener.onErrUpLoad("蓝牙连接失败,b="+b);
                }
            } else {
                mOnUpLoadListener.onErrUpLoad("蓝牙未配对");
            }

        } else if (mBtReadClient.getBtState() == 2) {
            if (mBtReadClient.disconnectBt()) {
                mOnUpLoadListener.onErrUpLoad("设备已断开连接");
            } else {
                mOnUpLoadListener.onErrUpLoad("断开连接失败");
            }
        }
    }

    private BtReaderClient mClient;

    /**
     * 断开连接
     */
    public void stopConnect() {
        try {
            if (mClient != null) {
                mClient.disconnectBt();
            }
            if (mBtReadClient != null) {
                mBtReadClient.disconnect();
                mBtReadClient.disconnectBt();
                Log.e("项目异常Kt8003", "------Kt8003断开连接------");
            }
        } catch (Exception e) {
            Log.e("项目异常", "------断开连接异常------" + e.toString());
            mOnUpLoadListener.onErrUpLoad("");
            e.printStackTrace();
        }

    }

    /**
     * KT8003 所需
     */
    class ReadAsync extends AsyncTask<Intent, Integer, IDCardItem> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected IDCardItem doInBackground(Intent... params) {
            if (mBtReadClient != null) {
                IDCardItem item = mBtReadClient.readCertWithBlocking();
                return item;
            } else {
                mOnUpLoadListener.onErrUpLoad("读取失败:mBtReadClient为空");
                return null;
            }
        }

        @Override
        protected void onPostExecute(IDCardItem result) {
            super.onPostExecute(result);
            updateResult(result);
        }
    }

    /**
     * KT8003 所需
     */
    private void updateResult(IDCardItem arg0) {

        if (arg0.retCode == 1) {
            updateView(arg0);
        } else {
            mOnUpLoadListener.onErrUpLoad(CardCode.errorCodeDescription(arg0.retCode));
        }
    }

    /**
     * KT8003 所需
     */
    private void updateView(IDCardItem item) {
        photo = item.picBitmap;
        photoHeard = BleGlobUtils.replaceBlank(
                BleGlobUtils.bitmapToBase64(photo)); //头像
        name = item.partyName.toString().trim(); //名字
        sex = item.gender; //性别
        nation = item.nation; //民族
        born = item.bornDay.substring(0, 4) + item.bornDay.substring(4, 6)
                + item.bornDay.substring(6, 8);  //出生年月日
        birth_year = item.bornDay.substring(0, 4);
        birth_month = item.bornDay.substring(4, 6);
        birth_day = item.bornDay.substring(6, 8);
        address = item.certAddress;//住址
        id_num = item.certNumber;//证件号
        sign_office = item.certOrg;//签发机关
        String expDate = item.expDate;
        String effDate = item.effDate;
        from = effDate.substring(0, 4) +
                effDate.substring(4, 6) +
                effDate.substring(6, 8);

        if (expDate.contains("长期")) {
            sign_data = item.effDate.substring(0, 4) + "."
                    + item.effDate.substring(4, 6) + "." +
                    item.effDate.substring(6, 8)
                    + "--" + expDate.trim();
            to = "长期";
        } else {
            to = expDate.substring(0, 4) +
                    expDate.substring(4, 6) +
                    expDate.substring(6, 8);
            sign_data = item.effDate.substring(0, 4) + "."
                    + item.effDate.substring(4, 6) + "." +
                    item.effDate.substring(6, 8) + "--" +
                    item.expDate.substring(0, 4) + "."
                    + item.expDate.substring(4, 6) + "."
                    + item.expDate.substring(6, 8);
        }
        Log.e("项目异常", name + "------1------" + id_num);
        stopConnect();
        bleHttpUtils.upLoadSfzPhoto(bleName, bleAddress,address, photoHeard, sex, id_num, nation,
                sign_office, to, name, from, born, sign_data, birth_year,
                birth_month, birth_day,  photo);
    }

    /**
     * 卡尔KT8003 账号密码  加密方法
     */
    private String getMD5(byte[] source) {
        String s = null;
        char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
                'e', 'f'};
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            md.update(source);
            byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数，
            // 用字节表示就是 16 个字节
            char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话，使用两个字符，
            // 所以表示成 16 进制需要 32 个字符
            int k = 0; // 表示转换结果中对应的字符位置
            for (int i = 0; i < 16; i++) { // 从第一个字节开始，对 MD5 的每一个字节
                // 转换成 16 进制字符的转换
                byte byte0 = tmp[i]; // 取第 i 个字节
                str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
                // >>> 为逻辑右移，将符号位一起右移
                str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
            }
            s = new String(str); // 换后的结果转换为字符串

        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }
}
